package a66weding.com.jiehuntong.fragment;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.ToolsWedRegisterActivity;
import a66weding.com.jiehuntong.beans.ItemTypeBean;
import a66weding.com.jiehuntong.common.CommonAdapter;
import a66weding.com.jiehuntong.common.MyViewHolder;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.view.MyFlowLayout;
import a66weding.com.jiehuntong.view.MyGridview;
import a66weding.com.jiehuntong.widgets.quicksearchlist.CityAdapter;
import a66weding.com.jiehuntong.widgets.quicksearchlist.CityData;
import a66weding.com.jiehuntong.widgets.quicksearchlist.CityItem;
import a66weding.com.jiehuntong.widgets.quicksearchlist.ContactItemComparator;
import a66weding.com.jiehuntong.widgets.quicksearchlist.ContactItemInterface;
import a66weding.com.jiehuntong.widgets.quicksearchlist.ContactListViewImpl;
import a66weding.com.jiehuntong.widgets.quicksearchlist.ContactsSectionIndexer;
import a66weding.com.jiehuntong.widgets.quicksearchlist.QuickIndexView;

/**
 * @version :
 * @creator : AxDu
 * @create-time : 2016/5/29
 * @description :
 */
public class Tools_WedReg_CityFragment extends BaseToolsDayPlanFragment implements TextWatcher, QuickIndexView.OnIndexChangeListener, View.OnClickListener {
    private ToolsWedRegisterActivity mWedregActivity;
    private View mCityView;
    private EditText mSearchEt;
    private QuickIndexView mIndexView;
    private ListView mMainListView;
    private TextView mSearchEmptyTv;
    private RelativeLayout mSearchEmptyRlay;
    private LinearLayout mBackLay;
    private RelativeLayout mQuickIndexRlay;

    private TextView tv_main;

    private String searchString;

    private Object searchLock = new Object();
    boolean inSearchMode = false;

    List<ContactItemInterface> contactList;
    List<ContactItemInterface> filterList;

    private ArrayList<ItemTypeBean> itemTypeList;

    private MyCityAdapter mLvAdapter;
    private String[] mHotCities;

    private static final int SEARCHRESULTSUCESS = 1;
    private static final int SEARCHRESULTFAIL = 2;


    @Override
    public View initView() {
        mWedregActivity = (ToolsWedRegisterActivity) mActivity;

        mCityView = View.inflate(mActivity, R.layout.tools_wedreg_cityfragment, null);

        mSearchEt = (EditText) mCityView.findViewById(R.id.et_search);
//        mListView = (ContactListViewImpl) mCityView.findViewById(R.id.lv_tools_wedreg);
        mIndexView = (QuickIndexView) mCityView.findViewById(R.id.qiv_sideBar);
        mMainListView = (ListView) mCityView.findViewById(R.id.lv_tools_wedreg_citylist);
        mSearchEmptyTv = (TextView) mCityView.findViewById(R.id.search_empty);
        mSearchEmptyRlay = (RelativeLayout) mCityView.findViewById(R.id.rlay_tools_wedregcity);
        mBackLay = (LinearLayout) mCityView.findViewById(R.id.llay_tools_wedregister_back);
        mQuickIndexRlay = (RelativeLayout) mCityView.findViewById(R.id.side_layout);


        mSearchEt.addTextChangedListener(this);
        mIndexView.setOnIndexChangeListener(this);
        mBackLay.setOnClickListener(this);


        return mCityView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
    }

    @Override
    public void initData() {


        itemTypeList = new ArrayList<ItemTypeBean>();
        mHotCities = new String[]
                {"北京", "上海", "杭州", "西安", "成都", "深圳",
                        "广州", "武汉", "南京", "重庆", "天津",
                        "苏州", "厦门", "三亚"};


//        itemTypeList.add(new ItemTypeBean(1,1,"body"));


        filterList = new ArrayList<ContactItemInterface>();

        contactList = mWedregActivity.getContactList();
        filterList.clear();
        for (ContactItemInterface item : contactList) {
            filterList.add(item);
        }
        ItemTypeBean itemType = null;
        for (int i = 0; i < filterList.size() + 1; i++) {
            if (i == 0) {
                itemType = new ItemTypeBean(0, 0, "letterheader");
            } else {
                itemType = new ItemTypeBean(i, 1, "letteritem");
            }
            itemTypeList.add(itemType);

        }

        if (itemTypeList != null && itemTypeList.size() > 0 && filterList != null) {
            mLvAdapter = new MyCityAdapter(itemTypeList, filterList);
            mMainListView.setAdapter(mLvAdapter);

        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.llay_tools_wedregister_back:
                mWedregActivity.getSupportFragmentManager().popBackStack();
                break;
            case R.id.infoRowContainer:
                ContactItemInterface item = (ContactItemInterface) view.getTag();
                mWedregActivity.setCityName(item.getDisplayInfo());
                mSearchEt.setText("");
//                filterList.clear();
//                contactList.clear();
                FragmentTransaction transaction = mWedregActivity.getSupportFragmentManager().beginTransaction();
                transaction.remove(this);
                mWedregActivity.getSupportFragmentManager().popBackStack();
                break;
            case R.id.btn_hotcity:
                String cityName = (String) view.getTag();
                mWedregActivity.setCityName(cityName);
                mWedregActivity.getSupportFragmentManager().popBackStack();
                break;

        }
    }


    public class MyCityAdapter extends BaseAdapter {
        private List<ItemTypeBean> typeList;
        private int resource; // store the resource layout id for 1 row
        private boolean inSearchMode = false;
        private List<ContactItemInterface> _items;

        private ContactsSectionIndexer indexer = null;


        public MyCityAdapter(List<ItemTypeBean> typeList, List<ContactItemInterface> _items) {
            this.typeList = typeList;

            Collections.sort(_items, new ContactItemComparator());

            setIndexer(new ContactsSectionIndexer(_items));
        }


        @Override
        public int getCount() {
            return typeList.size();
        }

        @Override
        public int getViewTypeCount() {
            return typeList.size();
        }

        @Override
        public int getItemViewType(int position) {
            return typeList.get(position).getType();
        }

        @Override
        public Object getItem(int position) {
            return typeList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            int type = typeList.get(position).getType();
            ViewHolder myHolder = null;
            switch (type) {
                case 0:
                    if (convertView == null) {
                        myHolder = new ViewHolder();
                        convertView = View.inflate(mWedregActivity, R.layout.item_header_citylist, null);

                        myHolder.mCurrentCityBtn = (Button) convertView.findViewById(R.id.btn_currentcity);
                        myHolder.mHotCityGv = (MyGridview) convertView.findViewById(R.id.gview_tools_wedreg_hotcity);

                        convertView.setTag(myHolder);
                    } else {
                        myHolder = (ViewHolder) convertView.getTag();
                    }
                    myHolder.mCurrentCityBtn.setText(mWedregActivity.getCityName());
                    final List<String> hotCities = Arrays.asList(mHotCities);
                    myHolder.mHotCityGv.setAdapter(new CommonAdapter<String>(mWedregActivity, hotCities, R.layout.item_city_view) {
                        @Override
                        public void convert(MyViewHolder holder, int position) {

                            Button cityBtn = (Button) holder.getView(R.id.btn_hotcity);
                            cityBtn.setText(hotCities.get(position));
                            cityBtn.setTag(cityBtn.getText().toString());
                            cityBtn.setOnClickListener(Tools_WedReg_CityFragment.this);

                        }
                    });

                    break;
                case 1:
                    myHolder = new ViewHolder();
                    ContactItemInterface item = filterList.get(position - 1);
                    if (convertView == null) {
                        convertView = View.inflate(mWedregActivity, R.layout.city_item, null);

                        myHolder.mCityNameTv = (TextView) convertView.findViewById(R.id.cityName);

                        myHolder.mSectionTv = (TextView) convertView.findViewById(R.id.sectionTextView);
                        myHolder.mSectionRlay = (RelativeLayout) convertView.findViewById(R.id.infoRowContainer);

                        convertView.setTag(myHolder);
                    } else {
                        myHolder = (ViewHolder) convertView.getTag();
                    }
                    myHolder.mSectionRlay.setTag(item);
                    myHolder.mSectionRlay.setOnClickListener(Tools_WedReg_CityFragment.this);

                    if (filterList != null && filterList.size() > 0) {


                        showSectionViewIfFirstItem(myHolder.mSectionTv, item, position - 1);

                        populateDataForRow(myHolder.mCityNameTv, item, position - 1);

                    }
                    break;
            }


            return convertView;
        }


        public void populateDataForRow(TextView parentView, ContactItemInterface item,
                                       int position) {
            View infoView = parentView.findViewById(R.id.infoRowContainer);


            parentView.setText(item.getDisplayInfo());
        }


        public void showSectionViewIfFirstItem(View rowView,
                                               ContactItemInterface item, int position) {
            TextView sectionTextView = (TextView) rowView;

            if (inSearchMode) {
                sectionTextView.setVisibility(View.GONE);
            } else {

                if (indexer.isFirstItemInSection(position)) {

                    String sectionTitle = indexer.getSectionTitle(item
                            .getItemForIndex());
                    sectionTextView.setText(sectionTitle);
                    sectionTextView.setVisibility(View.VISIBLE);

                } else
                    sectionTextView.setVisibility(View.GONE);
            }
        }


        public ContactsSectionIndexer getIndexer() {
            return indexer;
        }

        public void setIndexer(ContactsSectionIndexer indexer) {
            this.indexer = indexer;
        }

        public boolean isInSearchMode() {
            return inSearchMode;
        }

        public void setInSearchMode(boolean inSearchMode) {
            this.inSearchMode = inSearchMode;
        }


        class ViewHolder {
            MyGridview mHotCityGv;
            Button mCurrentCityBtn;
            ContactListViewImpl mCityLv;
            TextView mLvtopTv;
            MyFlowLayout mHotCityLay;

            TextView mCityNameTv;
            TextView mSectionTv;
            RelativeLayout mSectionRlay;

        }


    }


    @Override
    public void onIndexChanged(final String word) {
        if (!TextUtils.isEmpty(word)) {

            searchcity2(word);
        }

    }

    @Override
    public void onTouchUp() {

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        searchString = mSearchEt.getText().toString().trim().toUpperCase();

        mSearchEmptyTv.setVisibility(View.GONE);
        mSearchEmptyRlay.setVisibility(View.VISIBLE);

        if (TextUtils.isEmpty(searchString)) {
            filterList.clear();
            for (ContactItemInterface item : contactList) {
                filterList.add(item);
            }

            ItemTypeBean itemType = null;
            for (int i = 0; i < filterList.size() + 1; i++) {
                if (i == 0) {
                    itemType = new ItemTypeBean(0, 0, "letterheader");
                } else {
                    itemType = new ItemTypeBean(i, 1, "letteritem");
                }
                itemTypeList.add(itemType);

            }

            if (itemTypeList != null && itemTypeList.size() > 0 && filterList != null) {
                mLvAdapter = new MyCityAdapter(itemTypeList, filterList);
                mMainListView.setAdapter(mLvAdapter);

            }

            mQuickIndexRlay.setVisibility(View.VISIBLE);


        } else {

            new Thread() {
                @Override
                public void run() {
                    mHandler.removeCallbacksAndMessages(null);
                    searchcity(searchString);
                }
            }.start();

        }

    }


    public void searchcity(String word) {
        inSearchMode = (word.length() > 0);
        filterList.clear();
        if (inSearchMode) {

            for (ContactItemInterface item : contactList) {
                CityItem contact = (CityItem) item;
                boolean isPinyin = contact.getFullName().toUpperCase().indexOf(word) > -1;
                boolean isChinese = contact.getNickName().contains(word);

                if (isPinyin || isChinese) {
                    filterList.add(item);

                }
            }
            if (filterList.size() > 0) {
                mHandler.sendEmptyMessage(SEARCHRESULTSUCESS);
            } else {
                mHandler.sendEmptyMessage(SEARCHRESULTFAIL);
            }

        }

    }

    public void searchcity2(String word) {
        inSearchMode = (word.length() > 0);
        if (inSearchMode) {

            int sectionIndex = mLvAdapter.getIndexer().getSectionIndex(word);
            int positionForSection = mLvAdapter.getIndexer().getPositionForSection(sectionIndex);

            mMainListView.setSelection(positionForSection);

            String slecStr = filterList.get(positionForSection).getDisplayInfo();

        }

    }


    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SEARCHRESULTSUCESS:
                    if (inSearchMode) {

                        if (filterList != null) {
                            CityAdapter adapter = new CityAdapter(mWedregActivity, R.layout.city_item, filterList);

                            mMainListView.setAdapter(new CommonAdapter<ContactItemInterface>(mWedregActivity, filterList, R.layout.city_item) {

                                @Override
                                public void convert(MyViewHolder holder, int position) {
                                    ContactItemInterface contactItemInterface = filterList.get(position);
                                    String displayInfo = contactItemInterface.getDisplayInfo();
                                    RelativeLayout cityRlay = (RelativeLayout) holder.getView(R.id.infoRowContainer);

                                    cityRlay.setTag(contactItemInterface);
                                    cityRlay.setOnClickListener(Tools_WedReg_CityFragment.this);

                                    holder.setText(R.id.cityName, displayInfo);

                                }
                            });


                        }

                        mQuickIndexRlay.setVisibility(View.GONE);
                    }
                    break;
                case SEARCHRESULTFAIL:
                    mSearchEmptyTv.setVisibility(View.VISIBLE);
                    mSearchEmptyRlay.setVisibility(View.GONE);
                    mQuickIndexRlay.setVisibility(View.GONE);

                    break;
            }
        }
    };


}
